package com.guigu.eduservice.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.guigu.eduservice.entity.EquipmentType;
import com.guigu.eduservice.mapper.EquipmentTypeMapper;
import com.guigu.eduservice.service.EquipmentTypeService;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class EquipmentTypeImpl extends ServiceImpl<EquipmentTypeMapper, EquipmentType> implements EquipmentTypeService {

    @Override
    public List<EquipmentType> selectByParentId(Long parentId) {
        QueryWrapper<EquipmentType> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_id", parentId);
        List<EquipmentType> list = this.list(wrapper);
        return list;
    }

    @Override
    public List<EquipmentType> getTypeTree() {
        // 1. 查询所有顶级类型
        QueryWrapper<EquipmentType> wrapper = new QueryWrapper<>();
        wrapper.isNull("parent_id");
        List<EquipmentType> topTypes = this.list(wrapper);

        // 2. 为每个顶级类型递归设置子类型
        List<EquipmentType> typeTree = topTypes.stream()
                .map(this::buildChildren) // 调用递归方法
                .collect(Collectors.toList());

        return typeTree;
    }

    // 递归方法：为当前类型添加子类型，并继续递归子类型的子类型
    private EquipmentType buildChildren(EquipmentType parentType) {
        // 1. 查询当前类型的所有子类型
        List<EquipmentType> children = this.selectByParentId(parentType.getTypeId());

        // 2. 如果有子类型，继续递归设置子类型的子类型
        if (children != null && !children.isEmpty()) {
            List<EquipmentType> childTree = children.stream()
                    .map(this::buildChildren) // 递归调用，处理子类型的子类型
                    .collect(Collectors.toList());
            parentType.setChildren(childTree); // 给当前类型设置子类型
        }

        return parentType;
    }


}
